package com.magold.text;

import org.andengine.opengl.font.IFont;
import org.andengine.opengl.font.Letter;

public class MagoldFontUtils {

	public static float measureText(IFont pFont, CharSequence pText) {
		// Trim to find the start and end position.
		int pStart = 0;
		int pEnd = pText.length();
		for (; pStart < pEnd; pStart++) {
			if (!Character.isWhitespace(pText.charAt(pStart))) {
				break;
			}
		}
		
		for (; pEnd > pStart; pEnd--) {
			if (!Character.isWhitespace(pText.charAt(pEnd - 1))) {
				break;
			}
		}
		final int textLength = pEnd - pStart;
		
		/* Early exits. */
		if(pStart == pEnd) {
			return 0;
		} else if(textLength == 1) {
			return pFont.getLetter(pText.charAt(pStart)).mWidth;
		}

		Letter previousLetter = null;
		float width = 0;
		for(int pos = pStart; pos < pEnd; pos++) {
			final Letter letter = pFont.getLetter(pText.charAt(pos));
			if(previousLetter != null) {
				width += previousLetter.getKerning(letter.mCharacter);
			}
			previousLetter = letter;

			/* Check if this is the last character. */
			if(pos == (pEnd - 1)) {
				width += letter.mOffsetX + letter.mWidth;
			} else {
				width += letter.mAdvance;
			}
		}
		return width;
	}

}
